package com.csk.zsk.compents.action;

import java.math.BigDecimal;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.csk.zsk.commons.action.AjaxActionSupport;
import com.csk.zsk.commons.utils.encode.JsonBinder;
import com.csk.zsk.commons.utils.web.struts2.Struts2Utils;
import com.csk.zsk.compents.entity.Rating;
import com.csk.zsk.compents.entity.User;
import com.csk.zsk.compents.service.RatingService;
import com.csk.zsk.compents.utils.Constants;

@Controller
@Scope("prototype")
public class RatingAction extends AjaxActionSupport {

	private static final long serialVersionUID = -470025703653600762L;
	private static JsonBinder binder = JsonBinder.buildNonDefaultBinder();
	@Autowired
	private RatingService ratingService;
	private String id;
	private String userid;
	private String objid;
	private Integer num;

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getUserid() {
		return userid;
	}

	public void setUserid(String userid) {
		this.userid = userid;
	}

	public String getObjid() {
		return objid;
	}

	public void setObjid(String objid) {
		this.objid = objid;
	}

	public Integer getNum() {
		return num;
	}

	public void setNum(Integer num) {
		this.num = num;
	}

	public void addRating() {
		if (userid == null || userid.equals("")) {
			User user = (User) Struts2Utils.getSessionAttribute(Constants.USER_SESSION);
			userid = user.getId();

		}
		Rating rating = new Rating();
		rating.setUserid(userid);
		rating.setObjid(objid);
		rating.setNum(num);
		ratingService.saveRating(rating);

	}

	public void getRatingAVG() {
		String rlt = ratingService.getRatingAVG(objid);
		if (rlt == null) {
			rlt = "0";
		} else {
			BigDecimal bd = new BigDecimal(rlt);
			bd.setScale(1);
			double d = bd.doubleValue();

			Struts2Utils.renderText(new Double(d).toString());
		}
	}

	public void getUserRating() {
		if (userid == null || userid.equals("")) {
			User user = (User) Struts2Utils.getSessionAttribute(Constants.USER_SESSION);
			userid = user.getId();

		}
		Rating rating = ratingService.getUserRating(userid, objid);
		String json = binder.toJson(rating);
		Struts2Utils.renderJson(json);
	}

}
